import { Component, OnInit, ViewChild, OnDestroy } from '@angular/core';
import { _HttpClient, ModalHelper } from '@delon/theme';
import {SimpleTableButton, SimpleTableColumn, SimpleTableComponent} from '@delon/abc';
import { NzMessageService, NzModalService, NzTabChangeEvent, UploadFile, NzNotificationService } from 'ng-zorro-antd';
import { CommService } from 'app/service/comm/comm.service';
import { Constant, ServiceResult } from '@core/constant';
import { EmitterService } from 'app/service/emit.service';
import {ActivatedRoute, Router} from '@angular/router';
import { plService } from '../../../service/pl/pl.service';
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs';
import { TranslateService } from '@ngx-translate/core';
import { Timeout } from '@shared/descriptor/timeout';
import {formatDate} from "@angular/common";




@Component({
  selector: 'replan-list',
  templateUrl: './replan-list.component.html',
  styleUrls: ['./replan-list.component.less']
})
export class plListComponent implements OnInit, OnDestroy {
  // region 公共字段

  visible = false;
  // pageSize
  ps = 10;
  // 搜索表单
  q: any = {
    bpmStatus:"",

    cusName: '',
    cusMobile: '',
    orderInfo: '',
    orderNo: '',
    dateRange: null,
    startDate:'',
    endDate:''
  };

  loading = false;
  // 表格组件
  @ViewChild('st') st: SimpleTableComponent;
  // 表格数据url
  url = this.plService.list();
  // region end

  // 搜索区域显示/隐藏标记
  // 显示图片
  previewVisible = false;
  // 大图地址
  previewImage = '';
  imgSuffix = '';

  years = [];
  userGroups = [];
  brands = [];
  isAds = [{ text: '广告款', value: this.cnt.BoolUtil.TRUE}, { text: '普通款', value: this.cnt.BoolUtil.FALSE }];
  isCms = [{ text: '是', value: this.cnt.BoolUtil.TRUE}, { text: '否', value: this.cnt.BoolUtil.FALSE }];
  seasons = [];
  checkedList = [];
  data = [];
  bpmStatus =  [{text: '未还款', value: '1'}, {text: '已还款', value: '10'}];

  uploadUrl = this.plService.uploadProds();
  uploadDateUrl = this.plService.batchRepdate();


  columns: SimpleTableColumn[] = [
    // { title: '', index: 'key', type: 'checkbox' },
    // { title: '产品种类', index: 'proClass' },
    // { title: '融租类型', index: 'proType'},
    // { title: '车辆信息', index: 'orderInfo' },
    { title: '状态', index: 'bpmStatus', render: 'bpmStatus' },

    { title: '订单编号 ', index: 'orderNo' },
    { title: '客户姓名' , index: 'cusName' },
    { title: '期数', index: 'refPeriod' },
    { title: '总期数', index: 'refTotalPeriod' },
    { title: '还款日期', index: 'refDate' },
    { title: '期初金额', index: 'refFbenjin' },
    { title: '还款金额', index: 'refAmount' },
    { title: '还款方式', index: 'fxjOut02' },
    // { title: '代垫保险', index: 'fxjOut03' },

    { title: '剩余本金', index: 'refSybenjin' },
    { title: '备注', index: 'reMark' },
    // { title: 'id', index: 'id' },
    // { title: '年份', index: 'year' },
    // { title: '广告款', index: 'isAd', render: 'isAd' },
    // { title: '状态', index: 'status', type: 'badge', badge: {
    //     '1': { text: '上架', color: 'success' },
    //     '0': { text: '下架', color: 'error' }
    //   }
    // },
    {
        title: '操作',
        buttons: [
            {
              text: '还款',
              type: 'link',
              click: (record: any) => this.router.navigate(['/pl/replan/edit/'+record.id]),
              // iif: (item: any, btn: SimpleTableButton, column: SimpleTableColumn) => {
              //   return item.bpmStatus === '未还款'
              // }
            },{
              text: '逾期',
              type: 'link',
              click: (record: any) => this.router.navigate(['/pl/replan/yuqi/'+record.id]),
              iif: (item: any, btn: SimpleTableButton, column: SimpleTableColumn) => {
                return item.bpmStatus === '未还款'
              }
            }
            // ,{
            //   text: '催收',
            //   type: 'link',
            //   click: (record: any) => this.router.navigate(['/cspList/cspList/edit/'+record.id]),
            //   iif: (item: any, btn: SimpleTableButton, column: SimpleTableColumn) => {
            //     return item.bpmStatus === '未还款'
            //   }
            // }
        ]
    }
  ];

  constructor(
    private trans: TranslateService,
    public http: _HttpClient,
    public msg: NzMessageService,
    private modalSrv: ModalHelper,
    private comm: CommService,
    private cnt: Constant,
    private plService: plService,
    private emit: EmitterService,
    private router: Router,
    private modalService: NzModalService,
    private notice: NzNotificationService,
    private route: ActivatedRoute,

  ) {}
  syncing = false;
  lastDate = null;
  private sub: any;

  ngOnDestroy() {
    if (this.inter) {
      clearInterval(this.inter);
    }
  }

  inter
  ngOnInit() {

    this.imgSuffix = this.comm.getGoodsUrl();
    // 获取参数
    this.sub = this.route.params.subscribe(params => {
      let varinpur = params["id"];
      if(varinpur){
        this.q.orderNo = params["id"];
      }
    });
    this.emit.getMessage().subscribe(data => {
      if (data.text === 'RELOAD_GOODS_LIST') {
        this.st.load(1, this.q);
      }
    })

  }

  fullChange(val: boolean) {
    // this.scroll = val ? { y: '350px' } : { y: '230px' };
  }

  back() {
    this.router.navigate(['/prod/product/80']);
  }

  change(args: NzTabChangeEvent) {
        switch (args.index) {
          case 0:
            this.q.bpmStatus = "";
            break;
          case 1:
            this.q.bpmStatus = "未还款";
            break;
          case 2:
            this.q.bpmStatus = "已还款";
            break;

          default:
            break;
        }
      this.st.load(1, this.q);
  }

  showImage(src) {
    this.previewImage = src;
    this.previewVisible = true;
  }

  checkboxChange(list: any[]) {
    this.checkedList = list;
  }

  gotoAdd() {
    setTimeout(() => {
      this.router.navigate(['/prod/product/add']);
    }, 500);
  }

  @Timeout(500)
  gotoImg() {
    this.router.navigate(['/prod/product/upload']);
  }


  selectProd: {[propName: string]: any;} = {}
  selectUrl = null;

  view(record) {
    this.plService.getProduct(record.id).pipe(
      catchError(err => {
        return of(err);
      })
    ).subscribe(data => {
      this.selectProd = data.data;
      // 拼接图片地址
      this.selectUrl = this.comm.getGoodsUrl() + this.selectProd.img;
      this.visible = true;
    })

  }

  close(): void {
    this.visible = false;
  }



  cancel() {
    this.repdate = null;
  }
  repdate = null;



  uploadProd(info: { file: UploadFile }) {
    if (info.file.status === 'uploading') {
        this.loading = true;
    }
    if (info.file.status === 'done') {
        this.loading = false;
        this.notice.create('success', 'Success', info.file.response.data['successTip']);
        if (undefined !== info.file.response.data['failTip']) {
          this.notice.create('info', 'Info', info.file.response.data['failTip']);
        }
        this.st.load();
    }
    if (info.file.status === 'error') {
        this.loading = false;
      this.notice.create('error', 'Error', info.file.response.msg);
    }
  }


  dateChange(result: Date[]): void {
    if (result.length !== 0) {
      this.q.startDate = formatDate(result[0], 'yyyy-MM-dd', 'en-US');
      this.q.endDate = formatDate(result[1], 'yyyy-MM-dd', 'en-US');
    } else {
      this.q.startDate = '';
      this.q.endDate = '';
    }
  }



}
